package com.licoba.emoji;

import android.databinding.DataBindingUtil;
import android.databinding.ObservableInt;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import android.arch.lifecycle.ViewModelProvider;
import android.widget.Toast;

import com.licoba.emoji.base.BaseMainFragment;
import com.licoba.emoji.bean.Person;
import com.licoba.emoji.bean.User;
import com.licoba.emoji.databinding.ActivityMainBinding;
import com.licoba.emoji.event.TabSelectedEvent;
import com.licoba.emoji.ui.fragment.first.FirstFragment;
import com.licoba.emoji.ui.fragment.second.SecondFragment;
import com.licoba.emoji.ui.fragment.third.ThirdFragment;
import com.licoba.emoji.ui.view.BottomBar;
import com.licoba.emoji.ui.view.BottomBarTab;

import cn.bmob.v3.AsyncCustomEndpoints;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.CloudCodeListener;
import cn.bmob.v3.listener.SaveListener;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.tencent.qq.QQ;
import me.yokeyword.eventbusactivityscope.EventBusActivityScope;
import me.yokeyword.fragmentation.SupportActivity;
import me.yokeyword.fragmentation.SupportFragment;

public class MainActivity extends SupportActivity implements BaseMainFragment.OnBackToFirstListener {

    public static final int FIRST = 0;
    public static final int SECOND = 1;
    public static final int THIRD = 2;

    private SupportFragment[] mFragments = new SupportFragment[3];
    private BottomBar mBottomBar;  //底部按钮
    ActivityMainBinding binding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_main);

        /**
         * 获取栈内的fragment对象
         */
        SupportFragment firstFragment = findFragment(FirstFragment.class);

        if (firstFragment == null) {
            mFragments[FIRST] = FirstFragment.newInstance();
            mFragments[SECOND] = SecondFragment.newInstance();
            mFragments[THIRD] = ThirdFragment.newInstance();

            /**
             * 加载多个同级根Fragment,类似Wechat, QQ主页的场景
             */
            loadMultipleRootFragment(R.id.fl_container, FIRST,
                    mFragments[FIRST],
                    mFragments[SECOND],
                    mFragments[THIRD]);

        } else { //栈内存在 firstFragment
            // 这里库已经做了Fragment恢复,所有不需要额外的处理了, 不会出现重叠问题

            // 这里我们需要拿到mFragments的引用
            mFragments[FIRST] = firstFragment;
            mFragments[SECOND] = findFragment(SecondFragment.class);
            mFragments[THIRD] = findFragment(ThirdFragment.class);

        }

        initView();


//        binding.btnBmob.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//
//                AsyncCustomEndpoints ace =  new AsyncCustomEndpoints();
//                //第一个参数是云函数的方法名称，第二个参数是上传到云函数的参数列表（JSONObject cloudCodeParams），第三个参数是回调类
//                ace.callEndpoint("TestNet", new CloudCodeListener() {
//                    @Override
//                    public void done(Object o, BmobException e) {
////                        Toast.makeText(getApplicationContext(),"成功请求到云函数" ,Toast.LENGTH_SHORT).show();
//                        Toast.makeText(getApplicationContext(),o.toString() ,Toast.LENGTH_SHORT).show();
//                    }
//                });
//            } //end onclick
//        });
//
//        binding.btnGetEmoji.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                AsyncCustomEndpoints ace =  new AsyncCustomEndpoints();
//                //第一个参数是云函数的方法名称，第二个参数是上传到云函数的参数列表（JSONObject cloudCodeParams），第三个参数是回调类
//                ace.callEndpoint("getEmoji", new CloudCodeListener() {
//                    @Override
//                    public void done(Object o, BmobException e) {
////                        Toast.makeText(getApplicationContext(),"成功请求到云函数" ,Toast.LENGTH_SHORT).show();
//                        Toast.makeText(getApplicationContext(),o.toString() ,Toast.LENGTH_SHORT).show();
//                    }
//                });
//            }
//        });

    }

    public void initView() {
        binding.bottomBar
                .addItem(new BottomBarTab(this, R.mipmap.ic_bottom_first_check))
                .addItem(new BottomBarTab(this, R.mipmap.ic_bottom_first_check))
                .addItem(new BottomBarTab(this, R.mipmap.ic_bottom_first_check));

        binding.bottomBar.setOnTabSelectedListener(new BottomBar.OnTabSelectedListener() {
            @Override
            public void onTabSelected(int position, int prePosition) {
                showHideFragment(mFragments[position], mFragments[prePosition]);
            }

            @Override
            public void onTabUnselected(int position) {

            }

            @Override
            public void onTabReselected(int position) {
                {
                    final SupportFragment currentFragment = mFragments[position];
                    //返回内嵌在当前Fragment当中的FragmentManager，用于管理内嵌在当前的Fragment的Fragments。
                    //得到栈内Fragment个数
                    int count = currentFragment.getChildFragmentManager().getBackStackEntryCount();

                    // 如果不在该类别Fragment的主页,则回到主页;
                    if (count > 1) {
                        if (currentFragment instanceof FirstFragment) {
                            currentFragment.popToChild(FirstFragment.class, false);
                        } else if (currentFragment instanceof SecondFragment) {
                            currentFragment.popToChild(SecondFragment.class, false);
                        } else if (currentFragment instanceof ThirdFragment) {
                            currentFragment.popToChild(ThirdFragment.class, false);
                        }
                        return;
                    }


                    // 这里推荐使用EventBus来实现 -> 解耦
                    if (count == 1) {
                        // 在FirstPagerFragment中接收, 因为是嵌套的孙子Fragment 所以用EventBus比较方便
                        // 主要为了交互: 重选tab 如果列表不在顶部则移动到顶部,如果已经在顶部,则刷新
                        EventBusActivityScope.getDefault(MainActivity.this).post(new TabSelectedEvent(position));
                    }
                }
            }
        });

    }


    //返回到FirstFragment
    @Override
    public void onBackToFirstFragment() {
        binding.bottomBar.setCurrentItem(0);
    }
}
